package edu.upb.acs.jobsmaps.activity.search;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.*;
import edu.upb.acs.jobsmaps.R;
import edu.upb.acs.jobsmaps.activity.MainScreenActivity;
import edu.upb.acs.jobsmaps.voice.VoiceUtils;

import java.util.ArrayList;
import java.util.List;

public class SearchJobActivityVoice extends Activity {

    private static final String TAG = SearchJobActivityVoice.class.getName();

    private Spinner spinner;
    private EditText editBox;

    //will be 1 for spinner, 2 for editbox
    private int flag;

    private Button mbtSpeakSearchCriteria;
    private Button mbtSpeakSearchWord;
    private Button mbtSpeakSearchProfile;
    private Button mbtSpeakSearchDistance;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_job_voice);

        flag = 0;

        initializeVoiceData();

        Log.d(TAG, "Initialize activity SearchJobActivity");
    }

    private void initializeVoiceData() {
		final Activity activity = this;

        mbtSpeakSearchCriteria = (Button) findViewById(R.id.voiceSearchCriteria);
        mbtSpeakSearchCriteria.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                spinner = (Spinner) findViewById(R.id.searchCriteriaJobVoice);

                ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
                int nrElements = myAdap.getCount();

                List<String> valuesSpinner = new ArrayList<>();
                for (int i = 0; i < nrElements; i++) {
                    valuesSpinner.add(spinner.getItemAtPosition(i).toString());
                }

                VoiceUtils.speak(null, valuesSpinner, activity);
                flag = 1;
            }
        });

        mbtSpeakSearchWord = (Button) findViewById(R.id.voiceSearchWord);
        mbtSpeakSearchWord.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                editBox = (EditText) findViewById(R.id.searchWordJobVoice);
				VoiceUtils.speak(null, null, activity);
                flag = 2;
            }
        });

        mbtSpeakSearchProfile = (Button) findViewById(R.id.voiceSearchProfile);
        mbtSpeakSearchProfile.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                spinner = (Spinner) findViewById(R.id.searchJobProfileVoice);

                ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
                int nrElements = myAdap.getCount();

                List<String> valuesSpinner = new ArrayList<>();
                for (int i = 0; i < nrElements; i++) {
                    valuesSpinner.add(spinner.getItemAtPosition(i).toString());
                }

				VoiceUtils.speak(null, valuesSpinner, activity);
                flag = 1;
            }
        });

        mbtSpeakSearchDistance = (Button) findViewById(R.id.voiceSearchDistance);
        mbtSpeakSearchDistance.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                spinner = (Spinner) findViewById(R.id.searchJobDistanceVoice);

                ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
                int nrElements = myAdap.getCount();

                List<String> valuesSpinner = new ArrayList<>();
                for (int i = 0; i < nrElements; i++) {
                    valuesSpinner.add(spinner.getItemAtPosition(i).toString());
                }

                VoiceUtils.speak(null, valuesSpinner, activity);
                flag = 1;
            }
        });

        checkVoiceRecognition();
    }

    private void checkVoiceRecognition() {
        // Check if voice recognition is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            mbtSpeakSearchCriteria.setEnabled(false);
            mbtSpeakSearchWord.setEnabled(false);
            mbtSpeakSearchProfile.setEnabled(false);
            mbtSpeakSearchDistance.setEnabled(false);

            mbtSpeakSearchCriteria.setText("Voice recognizer not present");
            mbtSpeakSearchWord.setText("Voice recognizer not present");
            mbtSpeakSearchProfile.setText("Voice recognizer not present");
            mbtSpeakSearchDistance.setText("Voice recognizer not present");

            Toast.makeText(this, "Voice recognizer not present",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "Start activity");

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int screenWidth = (int) (metrics.widthPixels * 0.80);
        getWindow().setLayout(screenWidth, LinearLayout.LayoutParams.WRAP_CONTENT);

        Button search = (Button) findViewById(R.id.searchButtonJobVoice);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                final Spinner spinner = (Spinner) findViewById(R.id.searchCriteriaJobVoice);
                final String searchCriteria = (String) spinner.getSelectedItem();

                final EditText searchWordField = (EditText) findViewById(R.id.searchWordJobVoice);
                final String searchWord = searchWordField.getText().toString();

                final String profile = ((Spinner) findViewById(R.id.searchJobProfileVoice)).getSelectedItem().toString();
                final String distance = ((Spinner) findViewById(R.id.searchJobDistanceVoice)).getSelectedItem().toString();

                Log.d(TAG, "Search after searchCriteria = " + searchCriteria + ", searchWord = " + searchWord
                        + " , profile = " + profile + " , distance = " + distance);

                Intent i = new Intent(SearchJobActivityVoice.this,
                        MainScreenActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.putExtra("search_word_job", searchWord);
                i.putExtra("search_criteria_job", searchCriteria);
                i.putExtra("search_distance_job", distance);
                i.putExtra("search_profile_job", profile);

                startActivity(i);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VoiceUtils.VOICE_RECOGNITION_REQUEST_CODE)

            //If Voice recognition is successful then it returns RESULT_OK
            if (resultCode == RESULT_OK) {

                ArrayList<String> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                    // populate the Matches
                    if (flag == 1) {
                        ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
                        int nrElements = myAdap.getCount();

                        List<String> valuesSpinner = new ArrayList<>();
                        for (int i = 0; i < nrElements; i++) {
                            valuesSpinner.add(spinner.getItemAtPosition(i).toString());
                        }

                        for (int i = 0; i < valuesSpinner.size(); i++) {
                            for (int j = 0; j < textMatchList.size(); j++) {
                                Log.d(TAG, "textMatchList: " + textMatchList.get(j));
                                if (valuesSpinner.get(i).equalsIgnoreCase(textMatchList.get(j))) {
                                    spinner.setSelection(i);
                                }
                            }
                        }
                    } else if (flag == 2) {
                        editBox.setText(textMatchList.get(0));
                    }


                }
                //Result code for various error.
            } else if (resultCode == RecognizerIntent.RESULT_AUDIO_ERROR) {
                showToastMessage("Audio Error");
            } else if (resultCode == RecognizerIntent.RESULT_CLIENT_ERROR) {
                showToastMessage("Client Error");
            } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
                showToastMessage("Network Error");
            } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
                showToastMessage("No Match");
            } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
                showToastMessage("Server Error");
            }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Helper method to show the toast message
     */
    void showToastMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}
